import Koa from 'koa'
import render from 'koa-ejs'
import bodyParser from 'koa-bodyparser'
import os from 'os'
import { authenticate } from './middleware/authenticate.js'
import { trimBodyParams } from './middleware/tools.js'
import { router as siteRoute } from './routes/site.js'
import { router as userRoute } from './routes/user.js'
import { router as postRoute } from './routes/post.js'
import { router as dictRoute } from './routes/dict.js'
import { router as companyRoute } from './routes/company.js'
import { router as user2Route } from './routes/user2.js'

const app = new Koa()

app.keys = ['hO0TTQctIjSjNykY']

// 使用中间件
app.use(bodyParser())
app.use(authenticate)
app.use(trimBodyParams)
render(app, {
  root: './templates',
  layout: 'main',
  viewExt: 'ejs'
  // debug: process.env.NODE_ENV !== 'production' // 是否开启调试模式
})

app.use(siteRoute.routes()).use(siteRoute.allowedMethods())
app.use(userRoute.routes()).use(userRoute.allowedMethods())
app.use(postRoute.routes()).use(postRoute.allowedMethods())
app.use(dictRoute.routes()).use(postRoute.allowedMethods())
app.use(companyRoute.routes()).use(postRoute.allowedMethods())
app.use(user2Route.routes()).use(postRoute.allowedMethods())

app.listen(10000, function () {
  console.log(`http://${getNetworkIp()}:10000`)
})

function getNetworkIp() {
  let needHost = '' // 打开的host
  try {
    // 获得网络接口列表
    let network = os.networkInterfaces()
    // console.log("network",network)
    for (let dev in network) {
      let iface = network[dev]
      for (let i = 0; i < iface.length; i++) {
        let alias = iface[i]
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal
        ) {
          needHost = alias.address
        }
      }
    }
  } catch (e) {
    needHost = 'localhost'
  }
  return needHost
}

/* ·　登录／注册（本项目不开放注册，用固定的账号密码）。

·　查看文章列表。

·　查看文章详情。

·　发表文章。

·　编辑文章。

·　删除文章。

·　项目结构。 */
